from wechatpy.client.api import WeChatMaterial
from wechatpy.session import SessionStorage
from redis import StrictRedis
from flask import current_app

from .cache import get_weahter_cache
from .models import Vtuber, Moe


class WeChatStorage(SessionStorage):
    """wechat自定义缓存后端"""

    def __init__(self):
        self.redis = StrictRedis(db=1)

    def get(self, key, default=None):
        data = self.redis.get(key)
        return data.decode() if data else default

    def set(self, key, value, ex=None):
        if value is None:
            return
        self.redis.set(key, value, ex)

    def delete(self, key):
        self.redis.delete(key, None)


def get_media_id(filename):
    """
    从redis中获取media素材id,没有则重新上传并缓存
    :param filename: 要获取的文件名
    :return: media_id
    """
    print(filename)
    key = 'wordcloud:%s' % filename
    conn = current_app.redis_client
    media_id = conn.get(key)
    if not media_id:
        # 此处补充上传media代码
        with open(current_app.config['IMAGE_PATH']+filename+'.jpg', 'rb') as f:
            json_dict = WeChatMaterial(client=current_app.wechat_client).add(media_type='image', media_file=f)
            media_id = json_dict.get('media_id')
            conn.set(key, media_id)
        return media_id
    return media_id.decode()


def get_weather(city):
    """
    获取city天气返回
    :param city: 查询的城市名
    :return: content回复给微信的内容
    """
    json = get_weahter_cache(current_app.redis_client, city)
    data = json['data']
    msg = json['msg']

    if data:
        try:
            datatime = data['pm25']['dateTime']
            temp = []
            for info in data['weather'][0]['info'].values():
                temp.append(int(info[2]))
            temperature_min = min(*temp)
            temperature_max = max(*temp)
            realtime = data['realtime']
            weather_info = realtime['weather']['info']
            wind = realtime['wind']['direct']+realtime['wind']['power']
        except Exception as e:
            current_app.logger('天气信息解析失败:', e)
            return '获取天气失败了peko'
    else:
        return msg

    content = "今天的{0}天气情况是这样的peko\r\n"\
              "{1}\n" \
              "天气: {2}\n" \
              "气温: {3}-{4}℃\n" \
              "{5}".format(city, datatime, weather_info, temperature_min, temperature_max, wind)

    return content


def get_vtuber_info(keyword):
    """
    从返回查询的V的信息
    :param content: 查询的条件
    :return: str——> 回复的信息内容
    """
    vtb = Vtuber.query.get(1)
    moes = ''
    for moe in vtb.moes:
        moes += moe.moename + '、'
    nicknames = ''
    for nickname in vtb.nicknames:
        nicknames += nickname.nickname + '、'
    comments = ''
    for comment in vtb.comments:
        comments += comment.content + '\n'

    content = f"""
    姓名:	{vtb.name}
    < {vtb.jpname} >
    别号:{nicknames}
    发色	:{vtb.haircolor}
    瞳色	:{vtb.eyecolor}
    身高	:{vtb.height}cm
    年龄	:{vtb.age}岁
    生日	:{vtb.birthday}
    星座	:{vtb.constellation}
    萌点:{moes}
    评论:{comments}
    """
    return content

